import _ from 'underscore'
import dispatcher from 'lib/dispatcher'
import {Scope} from 'lib/scopeFactory'

import TimeStore from 'lib/stores/time-store'
import {coreApi,sortMap,propConfig,parseToTopbar} from '../apis/core-util'

var classifyTree = [{
  key:'domain'
},{
  key:'url',
  requireId:'domainId',
  ignoreOnRerender: true
}];

export default class MainScope extends Scope {
  constructor(){
    super();
    this.viewKey = 'avg_resp';
    this.$state = {
      topbar:{
        $id:'topbar1',
        loading:true
      },
      searchBoxShow: false,
      searchDomainId: undefined,
      searchTopbar: {
        none: true
      },
      sortOptions: _.chain(propConfig)
                    .pick('avg_resp','total_resp_time','total_receive_size','resp_count')
                    .map(function(v,k){
                      return {
                        key:k,
                        label:v.label
                      }
                    })
                    .value()
    };
    this.topbarApi = coreApi({
      limit:20,
      urlName:'httptransaction',
      classify:'domain',
      size:1
    },TimeStore.getValue,function(){
      return {
        viewKey:this.viewKey
      }
    }.bind(this),function (){
      return {order:sortMap[this.viewKey]}
    },function(){
      if(this.viewKey==='total_receive_size'){
        return {
          classifyKeyField:'receive',
          classifyCountField:'num'
        }
      }else{
        return {
          classifyKeyField:'time',
          classifyCountField:'num'
        }
      }
    });
    this.topbarSearchApi = coreApi({
      limit:20,
      urlName:'httptransaction',
      classify:'domain',
      size:1,
      domainId: () => this.$state.searchDomainId
    },TimeStore.getValue,function(){
      return {
        viewKey:this.viewKey
      }
    }.bind(this),function (){
      return {order:sortMap[this.viewKey]}
    },function(){
      if(this.viewKey==='total_receive_size'){
        return {
          classifyKeyField:'receive',
          classifyCountField:'num'
        }
      }else{
        return {
          classifyKeyField:'time',
          classifyCountField:'num'
        }
      }
    });
  }

  $toggle_searchbox({ show, callback }) {
    this.$state.searchBoxShow = show;
    this.$state.searchDomainId = undefined;
    this.$state.searchTopbar = {
      none: true
    };

    this.emit(callback);
  } // $toggle_searchbox

  $search_info({ show, callback, domainId, id }) {
    this.$state.searchBoxShow = show;
    this.$state.searchDomainId = domainId;
    this.$state.searchTopbar = {
      none: true
    };

    let needRequest = !!domainId;
    if (needRequest && this.$state.topbar.data && this.$state.topbar.data.length) {
      needRequest = !_.chain(this.$state.topbar.data)
                      .map(p => {
                        if (p.children && p.children.data) {
                          return [p, ...p.children.data];
                        } else {
                          return [p];
                        }
                      })
                      .flatten(true)
                      .some(p => {
                        if (id !== undefined) {
                          return p.id === id;
                        } else {
                          return p.id === domainId;
                        }
                      })
                      .value();
    }

    if (needRequest) {
      this.topbarSearchApi
          .fetch()
          .progress(() => this.$state.searchTopbar = {
            loading: true
          })
          .done((data, params) => {
            this.$state.searchTopbar = {
              data: parseToTopbar(data, params, {
                classifyTree: id ? [
                  {
                    key:'domain'
                  },
                  {
                    key:'url',
                    requireId:'domainId',
                    options: {
                      urlId: id
                    }
                  }
                ] : classifyTree
              })
            };
          })
          .fail(err => this.$state.searchTopbar = {
            error: err
          })
          .always(() => {
            this.emit(this.$state.searchTopbar.data.length ? callback : null);
          });
    }

    this.emit(domainId && !needRequest ? callback : null);
  } // $search_info

  fetch(){
    var _this = this
    this.topbarApi.fetch().then(function(data,params){
      _this.$state.topbar = {
        data:parseToTopbar(data,params,{
          classifyTree:classifyTree
        })
      }
    },function(err){
      _this.$state.topbar = {
        error:err
      }
    },function(params){
      _this.$state.topbar = {
        loading:true,
        params:params
      }
      _this.emit()
    }).always(function(){
      _this.emit()
    })
  }
  $settime(payload){
    this.fetch()
  }
  $changesort(payload){
    this.viewKey = payload.key;
    this.fetch()
  }
  $load(){
    this.fetch()
  }
}
